package net.ant.watercalc.web.service.impl;

import net.ant.watercalc.web.config.PropConfig;
import net.ant.watercalc.web.pojo.bo.MailBo;
import net.ant.watercalc.web.service.MailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

@Service
public class MailServiceImpl implements MailService {

    private static Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    PropConfig propConfig;

    @Override
    public boolean sendMail(MailBo mailBo) {
        MimeMessage message = mailSender.createMimeMessage();
        if (mailBo == null || mailBo.getTo() == null) {
            return false;
        }
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(propConfig.getFrom());
            helper.setTo(mailBo.getTo());
            helper.setSubject(mailBo.getSubject());
            helper.setText(mailBo.getContent(), true);

            helper.addAttachment("Guardsman-Antiscalant Proposal.pdf", mailBo.getInput());
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }

}
